package com.gsta.cdn.cdr.aspect;

import com.alibaba.fastjson.JSON;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Logger;

@Aspect
@Component
public class ControllerLog {

    private Logger log = Logger.getLogger(String.valueOf(getClass()));
    ThreadLocal<Long> startTime = new ThreadLocal<Long>();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Pointcut("execution(* com.gsta.cdn.cdr.controller..*(..))")
    private void controllerAspect(){}

    @Before(value = "controllerAspect()")
    public void methodBefore(JoinPoint joinPoint){
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        CloseableHttpClient httpClient=HttpClients.createDefault();

        log.info("[" + df.format(new Date()) + "] 请求内容:请求地址:" + request.getRequestURL().toString() + " | 请求方式:" + request.getMethod() +
                " | 请求类方法:" + joinPoint.getSignature() + " | 请求类方法参数:" + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "obj", pointcut = "controllerAspect()")
    public void methodAfterReturning(Object obj){
//        log.info("ResponseMsg:" + JSON.toJSONString(obj));
        log.info("请求处理时间为:" + (System.currentTimeMillis() - startTime.get()) + "ms");
    }

}
